/*
 * Project Name: showtao
 * File Name: DistrictValidator.java
 * Class Name: DistrictValidator
 *
 * Copyright 2014 showtao.com
 *
 * Licensed under the showtao.com
 *
 * http://showtao.com
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.showtao.front.validation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;

/**
 * Class Name: DistrictValidator
 * <p>
 * Description: the distict validator, <br>
 * the single blank check of field not be dealed in here
 * 
 * @author minhuang
 * 
 */

public class DistrictValidator implements ConstraintValidator<DistrictCheck, Object> {
    private String country;
    private String state;
    private String city;

    public void initialize(DistrictCheck check) {
        this.country = check.country();
        this.state = check.state();
        this.city = check.city();
    }

    public boolean isValid(Object object, ConstraintValidatorContext context) {
        try {
            final String country = BeanUtils.getProperty(object, this.country);
            final String state = BeanUtils.getProperty(object, this.state);
            final String city = BeanUtils.getProperty(object, this.city);

            // all of them are blank or not
            if ((StringUtils.isBlank(country) && StringUtils.isBlank(state) && StringUtils.isBlank(city))
                    || (StringUtils.isNotBlank(country) && StringUtils.isNotBlank(state) && StringUtils
                            .isNotBlank(city))) {
                return true;
            }
            // the country is not blank
            if (StringUtils.isNotBlank(country)
                    && ((StringUtils.isBlank(state) && StringUtils.isBlank(city)) || (StringUtils.isNotBlank(state) && StringUtils
                            .isBlank(city)))) {
                return true;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }
}
